/*
 * @Description    : 日志记录函数，用于记录异常日志到柠聚开发平台（www.21ds.cn）
 * @Author         : QianLong
 * @Date           : 2023-04-06 10:21:37
 * @LastEditors    : QianLong
 * @Site           : http://www.21ds.cn
 * @LastEditTime   : 2023-10-21 12:42:13
 */
import CryptoJS from 'crypto-js'
import { pushErrorLog } from '@/api/common'
export default {
  filterNull: function (data) {
    return data == undefined || data == null ? '' : data
  },
  devSignature: function (data, secretKey) {
    // Remove the 'sign' key from the data object
    delete data['sign']

    // Sort the data by key
    const sortedData = Object.keys(data)
      .sort()
      .reduce((obj, key) => {
        obj[key] = data[key]
        return obj
      }, {})

    let queryString = Object.keys(sortedData)
      .map(function (key) {
        return key + '=' + encodeURIComponent(sortedData[key])
      })
      .join('&')

    const queryStringWithSecret = queryString + secretKey

    const signature = CryptoJS.SHA256(queryStringWithSecret).toString()

    // Return the signature
    return signature
  },
  getCurrentDateTime: function () {
    const now = new Date()
    const year = now.getFullYear()
    const month = ('0' + (now.getMonth() + 1)).slice(-2)
    const day = ('0' + now.getDate()).slice(-2)
    const hours = ('0' + now.getHours()).slice(-2)
    const minutes = ('0' + now.getMinutes()).slice(-2)
    const seconds = ('0' + now.getSeconds()).slice(-2)
    return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`
  },
  generateRequestId: function () {
    const timestamp = Date.now().toString(36)
    const randomString = Math.random().toString(36).substring(2, 8)
    return `${timestamp}_${randomString}`
  },
  getPath: function () {
    const route = window.location.href
    return route
  },
  deviceInfo: function () {
    const browserInfo = {
      userAgent: navigator.userAgent,
      appName: navigator.appName,
      appVersion: navigator.appVersion,
      platform: navigator.platform
    }
    return browserInfo
  },
  pushVueErrorLog: function (data) {
    var postData = {}
    postData['error'] = data
    var info = this.deviceInfo()
    postData['agent'] = info['userAgent']
    postData['app_name'] = info['appName']
    postData['platform'] = info['platform']
    postData['app_version'] = info['appVersion']
    postData['lsi_id'] = 'LSI4917487336395350'
    postData['time'] = this.getCurrentDateTime()
    postData['path'] = this.getPath()
    for (let key in postData) {
      postData[key] = btoa(postData[key])
    }
    postData['sign'] = this.devSignature(
      postData,
      'MARH62r5kxfkZDDSDQysKiAXyQSX7ZbGwA2bYNzPEjctCMjzmMKJ2TPsGyYrB348'
    )
    console.log(postData)
    pushErrorLog(postData)
      .then((res) => {
        console.log(res)
      })
      .catch((err) => {
        console.log(err)
      })
  }
}
